package com.javasea.log4j2.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 统一处理MDC
 *
 * @author: 伍波
 * @Date: 2023/3/15 10:51
 * @Version 1.0
 *
 * @version 1.0 2023/3/15 10:51  新建
 */
@Component
public class LogInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "traceId";

    private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String xForwardedForHeader = request.getHeader("X-Forwarded-For");
        String remoteIp = request.getRemoteAddr();
        String traceId = UUID.randomUUID().toString();
        MDC.put(TRACE_ID, traceId);
        LOGGER.info("client ip:{}, X-Forwarded-For:{}", remoteIp, xForwardedForHeader);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String traceId = MDC.get(TRACE_ID);
        LOGGER.info("remove traceId ({}) from logger", traceId);
        MDC.remove(TRACE_ID);
    }

}
